﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using FamilyTreeProject.Data.SqlServer;
using FamilyTreeProject.Web.Components;
using Castle.MicroKernel;
using FamilyTreeProject.Data;
using System.Data;
using Castle.Core;
using System.IO;
using FamilyTreeProject.Data.GEDCOM;

namespace FamilyTreeProject.Web
{
    public class FamilyTreeProjectApplication : System.Web.HttpApplication
    {
        #region Public Static Properties

        internal static IServiceContainer Services { get; set; }

        #endregion

        #region Private Methods

        private void RegisterServices(IKernel kernel)
        {
            string GEDCOMTestFilePath = @"D:\My Projects\Family Tree Project\Source\FamilyTreeProject.Web\Test Files";
            string GEDCOMFileName = "Test.ged";
            string fileName = Path.Combine(GEDCOMTestFilePath, GEDCOMFileName);

            //Func<IDbConnection> connectionFactory = DataUtil.GetConnectionFactory("FamilyTreeProject");
            //kernel.AddComponentInstance<Func<IDbConnection>>(connectionFactory);
            //kernel.AddComponent<SqlRepository<Individual>>(typeof(IRepository<Individual>), LifestyleType.Transient);

            kernel.AddComponentInstance("GEDCOMRepository",typeof(IRepository<Individual>),new GEDCOMRepository<Individual>(fileName));
            
            kernel.AddComponent<IndividualsService>(typeof(IIndividualsService));
        }

        #endregion

        #region Public Static Methods

        public static void RegisterRoutes(RouteCollection routes)
        {
            // Note: Change the URL to "{controller}.mvc/{action}/{id}" to enable
            //       automatic support on IIS6 and IIS7 classic mode
            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }, // Parameter defaults
                new { controller = @"[^\.]*" }                          // Parameter constraints
            );
        }

        #endregion

        #region Event Handlers

        protected void Application_Start()
        {
            // Setup Castle MicroKernel
            DefaultKernel kernel = new DefaultKernel();
            RegisterServices(kernel);

            // Set up service container
            Services = new CastleServiceContainer(kernel);

            // Register the controller factory
            ControllerBuilder.Current.SetControllerFactory(new ServiceContainerControllerFactory(Services));

            // Register Routes
            RegisterRoutes(RouteTable.Routes);
            //RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
        }

        #endregion

    }
}